import tkinter as tk
import requests
import threading


def send_request():
    def perform_request():
        url = url_entry.get()
        try:
            data = eval(data_entry.get())
            response = requests.post(url, json=data)
            status = f"状态码: {response.status_code}\n响应内容: {response.json()}"
            result_text.delete(1.0, tk.END)
            result_text.insert(tk.END, status)
            if response.status_code == 200:
                # 请求成功，清空数据输入框
                data_entry.delete(0, tk.END)
                # 将焦点聚焦到数据输入框
                data_entry.focus_set()
        except Exception as e:
            error = f"请求发生错误: {e}"
            result_text.delete(1.0, tk.END)
            result_text.insert(tk.END, error)

    # 创建并启动新线程执行网络请求
    request_thread = threading.Thread(target=perform_request)
    request_thread.start()


def on_enter_press(event):
    send_request()


def clear_result_text():
    result_text.delete(1.0, tk.END)


# 创建主窗口
root = tk.Tk()
root.title("API 发送端")

# 创建标签和输入框
url_label = tk.Label(root, text="请求 URL:")
url_label.pack()
url_entry = tk.Entry(root, width=50)
url_entry.insert(0, "http://127.0.0.1:5000/api/test")
url_entry.pack()
# 为 URL 输入框绑定回车键事件
url_entry.bind("<Return>", on_enter_press)

data_label = tk.Label(root, text="请求数据 (JSON 格式):")
data_label.pack()
data_entry = tk.Entry(root, width=50)
data_entry.insert(0, '{"name": "John", "age": 30}')
data_entry.pack()
# 为数据输入框绑定回车键事件
data_entry.bind("<Return>", on_enter_press)

# 创建发送按钮
send_button = tk.Button(root, text="发送请求", command=send_request)
send_button.pack()

# 创建显示结果的文本框
result_text = tk.Text(root, height=10, width=50)
result_text.pack()

# 创建右键菜单
right_click_menu = tk.Menu(root, tearoff=0)
right_click_menu.add_command(label="清除历史数据", command=clear_result_text)


def show_right_click_menu(event):
    right_click_menu.post(event.x_root, event.y_root)


# 为结果文本框绑定右键点击事件
result_text.bind("<Button-3>", show_right_click_menu)

# 运行主循环
root.mainloop()